<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button id="connBtn">Connect</button>
<input type="text" id="msg">
<button id="sendBtn" onclick="send()">Send</button>
<button id="closeBtn" onclick="closeWebsocket()">Close</button>
<div id="message">
</div>
</body>

<script>
    var ws = null;
    if ('WebSocket' in window){
        ws = new WebSocket("ws:localhost:8891/plumelog/websocket")
    }else {
        alert("Browser does not support");
    }
    var connBtn = document.getElementById("connBtn");
    var sendBtn = document.getElementById("sendBtn");
    var closeBtn = document.getElementById("closeBtn");
    // Connect安生错误的回调方法
    ws.onerror = function () {
        setMessageInnerHTML("WEBSOCKET link error occurred");
    }
    // Connect Ok 的回调方法
    ws.onopen = function (ev) {
        setMessageInnerHTML("WebSocket connection succeeded!");
    }
    // 收到消息的回调方法
    ws.onmessage = function (ev) {
        console.log(1)
        setMessageInnerHTML(ev.data);
    }
    // ConnectClose的回调方法
    ws.onclose = function () {
        setMessageInnerHTML("WebSocket connection closed");
    }
    // 监听窗口Close事 ，PreventConnect没断Close窗口。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    // 将消息显示在网Page上
    function setMessageInnerHTML(innerHtml){
        document.getElementById("message").innerHTML += innerHtml + '<br />'
    }
    // ClosewebsocketConnect
    function closeWebsocket(){
        ws.close();
    }
    // Send消息
    function send(){
        var message = document.getElementById("msg").value;
        ws.send(message);
    }
</script>
</html>